/**
 * May 5, 2014 4:56:47 PM
 */
package elitech.vietnam.copyweatherfashion.fragments;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.copyweatherfashion.LoginActivity;
import elitech.vietnam.copyweatherfashion.MainActivity;
import elitech.vietnam.copyweatherfashion.R;
import elitech.vietnam.copyweatherfashion.adapters.ShopContentAdapter;
import elitech.vietnam.copyweatherfashion.adapters.ShopRecentAdapter;
import elitech.vietnam.copyweatherfashion.config.Const;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment.ConfirmDialogClick;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment.Type;
import elitech.vietnam.copyweatherfashion.dialog.WarningDialogFragment;
import elitech.vietnam.copyweatherfashion.entities.Post;
import elitech.vietnam.copyweatherfashion.entities.Product;
import elitech.vietnam.copyweatherfashion.entities.Store;
import elitech.vietnam.copyweatherfashion.utilities.MyCallable;
import elitech.vietnam.copyweatherfashion.widget.ButtonLike;
import elitech.vietnam.copyweatherfashion.widget.ExpandableHeightGridView;
import elitech.vietnam.copyweatherfashion.widget.ExpandableHeightListView;
import elitech.vietnam.copyweatherfashion.wsclient.Service;

/**
 * @author Cong
 *
 */
public class StorePostFragment extends MyAbstractFragment implements View.OnClickListener, ConfirmDialogClick, OnItemClickListener {
	
	private static final int TASKS = 3;

	MainActivity mActivity;
	
	ExpandableHeightListView mLvContent;
	ExpandableHeightGridView mGvRecent;
	TextView mTxtName, mTxtProfile;
	ImageView mImgAvatar;
	ButtonLike mBtnLike;
	ShopContentAdapter mContentAdapter;
	ShopRecentAdapter mRecentAdapter;

	ArrayList<Object> mListContent = new ArrayList<Object>();
	ArrayList<Post> mListRecent = new ArrayList<Post>();
	Store mStore;
	
	int mTask = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActivity = (MainActivity) getActivity();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.shop_post, container, false);
		
		mLvContent = (ExpandableHeightListView) view.findViewById(R.id.shoppost_lvContent);
		mGvRecent = (ExpandableHeightGridView) view.findViewById(R.id.shoppost_gvRecent);
		mTxtName = (TextView) view.findViewById(R.id.shoppost_txtName);
		mTxtProfile = (TextView) view.findViewById(R.id.shoppost_txtProfile);
		mImgAvatar = (ImageView) view.findViewById(R.id.shoppost_imgAvatar);
		mBtnLike = (ButtonLike) view.findViewById(R.id.shoppost_btnLike);
		
		mLvContent.setExpanded(true);
		mContentAdapter = new ShopContentAdapter(mActivity, R.layout.layout_shopitem, mListContent);
		mLvContent.setAdapter(mContentAdapter);
		mGvRecent.setExpanded(true);
		mRecentAdapter = new ShopRecentAdapter(mActivity, R.layout.layout_recentitem, mListRecent);
		mGvRecent.setAdapter(mRecentAdapter);
		mGvRecent.setOnItemClickListener(this);

		mTxtName.setOnClickListener(this);
		mImgAvatar.setOnClickListener(this);
		mBtnLike.setOnClickListener(this);
		
		return view;
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		if (mActivity.mShopPost == null)
			throw new NullPointerException("Must set MainActivity mShopPost first");
	}
	
	@Override
	public void onStart() {
		super.onStart();
		/*
		 * Initialize header view
		 */
		Log.w("mActivity.mShopPost", mActivity.mShopPost.toString());
		mActivity.mBtnBack.setVisibility(View.VISIBLE);
		mActivity.mBtnNotify.setVisibility((mActivity.mUser!=null) ? View.VISIBLE : View.GONE);
		
		mBtnLike.setData(mActivity.mShopPost.Liked(), mActivity.mShopPost.Likes);
		mTask = 0;
		new GetProduct().execute();
		new GetStore().execute();
		new GetRecent().execute();
	}

	@Override
	public void onResume() {
		super.onResume();
		/**
		 * Implement onActivityResult Base on MainActivity.mRequestCode and
		 * MainActivity.mResultIntent
		 */
		if (mActivity.mRequestCode == MainActivity.REQUEST_LOGIN && mActivity.mResultIntent != null) {
			mActivity.getLoggedMemberInfo(mActivity.mResultIntent.getIntExtra(LoginActivity.EXTRA_USERID, -1),
					new MyCallable() {
						@Override
						public void call() {
							mActivity.mBtnNotify.setVisibility((mActivity.mUser!=null) ? View.VISIBLE : View.GONE);
							new GetPost().execute(mActivity.mShopPost.Id);
						}
					});
		}
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.shoppost_txtName:
			String link = mActivity.mShopPost.Link;
			if (link == null) {
				Toast.makeText(mActivity, R.string.address_is_not_valid, Toast.LENGTH_SHORT).show();
				return;
			}
			link = (link.startsWith("http://") || link.startsWith("https://")) ? link : ("http://" + link);
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
			mActivity.startActivity(intent);
			break;
		case R.id.shoppost_imgAvatar:
			// TODO: open dialog
			break;
		case R.id.shoppost_btnLike:
			if (mActivity.mUser == null) {
				Intent intent1 = new Intent(mActivity, LoginActivity.class);
				mActivity.startActivityForResult(intent1, MainActivity.REQUEST_LOGIN);
			} else {
				String ms = (mActivity.mShopPost.Liked())
				? getString(R.string.do_you_want_to_unlike_this_post_)
				: getString(R.string.do_you_want_to_like_this_post_);
				new ConfirmDialogFragment.Builder()
					.setMessage(ms)
					.setTargetFragment(this)
					.setType(Type.FRAGMENT)
					.build().show(getFragmentManager());
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void yesClick() {
		new LikeTask().execute();
	}

	@Override
	public void noClick() {
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		switch (parent.getId()) {
		case R.id.shoppost_gvRecent:
			mActivity.mShopPost = mListRecent.get(position);
			mBtnLike.setData(mActivity.mShopPost.Liked(), mActivity.mShopPost.Likes);
			mTask = 0;
			new GetProduct().execute();
			new GetStore().execute();
			new GetRecent().execute();
			((ScrollView) mMain).smoothScrollTo(0, 0);
			break;
		default:
			break;
		}
	}
	
	private void finishTask() {
		mTask += 1;
		if (mTask == TASKS)
			showMain();
		Log.w(getClass().getSimpleName(), mTask + "");
	}
	
	class GetProduct extends AsyncTask<Integer, Integer, Boolean> {
		ArrayList<Product> rs = new ArrayList<Product>();
		@Override
		protected void onPreExecute() {
			if (mMain.getVisibility() != View.GONE)
				showLoading();
		}
		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				rs = new Service().getListProduct(mActivity.mShopPost.Id);
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}
		@Override
		protected void onPostExecute(Boolean result) {
			if (!isVisible())
				return;
			if (result) {
				mListContent.clear();
				if (rs == null || rs.isEmpty())
					mListContent.add(mActivity.mShopPost);
				else
					mListContent.addAll(rs);
				mContentAdapter.notifyDataSetChanged();
			} else {
				new WarningDialogFragment.Builder()
				.setMessage(getString(R.string.cannot_connect_to_server))
				.build().show(getFragmentManager());
			}
			finishTask();
		}
	}
	
	class GetStore extends AsyncTask<Integer, Integer, Store> {
		@Override
		protected void onPreExecute() {
			if (mMain.getVisibility() != View.GONE)
				showLoading();
		}
		@Override
		protected Store doInBackground(Integer... params) {
			try {
				return new Service().getInfoStore(mActivity.mShopPost.StoreId);
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return null;
			}
		}
		@Override
		protected void onPostExecute(Store result) {
			if (!isVisible())
				return;
			if (result != null) {
				mStore = result;
				UrlImageViewHelper.setUrlDrawable(mImgAvatar, Const.SERVER_IMAGE_THUMB_URL + mStore.Image, R.drawable.avatar);
				mTxtName.setText(mStore.Name);
				mTxtProfile.setText(mStore.Profile);
			} else {
				new WarningDialogFragment.Builder()
				.setMessage(getString(R.string.cannot_connect_to_server))
				.build().show(getFragmentManager());
			}
			finishTask();
		}
	}

	class GetRecent extends AsyncTask<Integer, Integer, Boolean> {
		ArrayList<Post> rs = new ArrayList<>();
		@Override
		protected void onPreExecute() {
			if (mMain.getVisibility() != View.GONE)
				showLoading();
		}
		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				rs = new Service().getThumbnailFashion(mActivity.mShopPost.StoreId, mActivity.mShopPost.Date, 6);
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}
		@Override
		protected void onPostExecute(Boolean result) {
			if (!isVisible())
				return;
			if (result && rs != null) {
				mListRecent.clear();
				mListRecent.addAll(rs);
				mRecentAdapter.notifyDataSetChanged();
			} else {
				new WarningDialogFragment.Builder()
				.setMessage(getString(R.string.cannot_connect_to_server))
				.build().show(getFragmentManager());
			}
			finishTask();
		}
	}

	class LikeTask extends AsyncTask<Integer, Integer, Integer> {
		@Override
		protected void onPreExecute() {
			mBtnLike.setEnabled(false);
		}
		@Override
		protected Integer doInBackground(Integer... params) {
			try {
				return new Service().newLike(mActivity.mUser.Id, mActivity.mShopPost.Id, mActivity.mShopPost.Liked() ? -1 : 1);
			} catch (IOException | XmlPullParserException e) { e.printStackTrace();
				return null;
			}
		}
		@Override
		protected void onPostExecute(Integer result) {
			if (!isVisible())
				return;
			mBtnLike.setEnabled(true);
			if (result == null || result == -1) {
				new WarningDialogFragment.Builder()
				.setMessage(getString(R.string.cannot_connect_to_server))
				.build().show(getFragmentManager());
			} else {
				mActivity.mShopPost.Liked(!mActivity.mShopPost.Liked());
				mActivity.mShopPost.Likes = result;
				mBtnLike.setData(mActivity.mShopPost.Liked(), mActivity.mShopPost.Likes);
			}
		}
	}
	

	class GetPost extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected void onPreExecute() {
			if (mMain.getVisibility() != View.GONE)
				showLoading();
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				mActivity.mShopPost = new Service().getPostByID(params[0],
						(mActivity.mUser != null) ? mActivity.mUser.Id : -1, Const.COUNTRYCODE);
			} catch (IOException | XmlPullParserException e) {
				return false;
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (!isVisible())
				return;
			if (!result) {
				new WarningDialogFragment.Builder().setMessage(getString(R.string.cannot_connect_to_server)).build()
						.show(getFragmentManager());
			} else {
				mTask = 0;
				new GetProduct().execute();
				new GetStore().execute();
				new GetRecent().execute();

				mActivity.mBtnNotify.setVisibility((mActivity.mUser!=null) ? View.VISIBLE : View.GONE);
				mBtnLike.setData(mActivity.mShopPost.Liked(), mActivity.mShopPost.Likes);
				
				mActivity.mRequestCode = -1;
				mActivity.mResultIntent = null;
			}
		}
	}
}
